package com.hanthink.system.service.impl.pc;

import java.util.List;

import com.hanthink.common.exception.CustomException;
import com.hanthink.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hanthink.system.domain.pc.EmFaultCode;
import com.hanthink.system.domain.pc.EmFaultType;
import com.hanthink.system.domain.pc.EmTask;
import com.hanthink.system.mapper.EmFaultCodeMapper;
import com.hanthink.system.mapper.EmFaultTypeMapper;
import com.hanthink.system.service.pc.IEmFaultTypeService;

/**
 * 故障类型Service业务层处理
 * 
 * @author hanthink
 * @date 2021-01-21
 */
@Service
public class EmFaultTypeServiceImpl implements IEmFaultTypeService {
	@Autowired
	private EmFaultTypeMapper emFaultTypeMapper;

	@Autowired
	private EmFaultCodeMapper emFaultCodeMapper;

	/**
	 * 查询故障类型
	 * 
	 * @param id 故障类型ID
	 * @return 故障类型
	 */
	@Override
	public EmFaultType selectEmFaultTypeById(Long id) {
		return emFaultTypeMapper.selectEmFaultTypeById(id);
	}

	/**
	 * 查询故障类型列表
	 * 
	 * @param emFaultType 故障类型
	 * @return 故障类型
	 */
	@Override
	public List<EmFaultType> selectEmFaultTypeList(EmFaultType emFaultType) {
		return emFaultTypeMapper.selectEmFaultTypeList(emFaultType);
	}

	/**
	 * 新增故障类型
	 * 
	 * @param emFaultType 故障类型
	 * @return 结果
	 */
	@Override
	public int insertEmFaultType(EmFaultType emFaultType) {
		EmFaultType queryCode = new EmFaultType();
		queryCode.setFaultCode(emFaultType.getFaultCode());
		List<EmFaultType> list = emFaultTypeMapper.selectEmFaultTypeList(queryCode);
		if (list.size() > 0) {
			throw new CustomException(String.format("故障代码:" + emFaultType.getFaultCode() + "已存在，请核实"));
		}

		emFaultType.setCreateTime(DateUtils.getNowDate());
		return emFaultTypeMapper.insertEmFaultType(emFaultType);
	}

	/**
	 * 修改故障类型
	 * 
	 * @param emFaultType 故障类型
	 * @return 结果
	 */
	@Override
	public int updateEmFaultType(EmFaultType emFaultType) {
		return emFaultTypeMapper.updateEmFaultType(emFaultType);
	}

	/**
	 * 批量删除故障类型
	 * 
	 * @param ids 需要删除的故障类型ID
	 * @return 结果
	 */
	@Override
	public int deleteEmFaultTypeByIds(Long[] ids) {
		for (Long id : ids) {
			EmFaultType dictType = selectEmFaultTypeById(id);
			EmFaultCode queryCode = new EmFaultCode();
			queryCode.setFaultCode(dictType.getFaultCode());
			List<EmFaultCode> list = emFaultCodeMapper.selectEmFaultCodeList(queryCode);
			if (list.size() > 0) {
				for (EmFaultCode code : list) {
					emFaultCodeMapper.deleteEmFaultCodeById(code.getId());
				}
			}
//			if (emFaultCodeMapper.countCodeByType(dictType.getFaultCode()) > 0) {
//				throw new CustomException(String.format("%1$s已存在故障任务不能删除", dictType.getFaultCode()));
//			}
		}
		return emFaultTypeMapper.deleteEmFaultTypeByIds(ids);
	}

	/**
	 * 删除故障类型信息
	 * 
	 * @param id 故障类型ID
	 * @return 结果
	 */
	@Override
	public int deleteEmFaultTypeById(Long id) {
		return emFaultTypeMapper.deleteEmFaultTypeById(id);
	}
}
